#include <stdio.h>

#include "nuclei_sdk_hal.h"

#define SPI0_SCKMODE_CPOL 1
#define SPI0_SCKMODE_CPHA 0

uint8_t send_n=0,receive_n=0;

uint8_t spi_transmit_receive(uint8_t tx)
{
    QSPI_TXDATA(QSPI0)=tx;
    while(QSPI_STATUS(QSPI0) & (1<<0));
    return QSPI_RXDATA(QSPI0) & 0xff;
}

void QSPI0_handler(void)
{
//	printf("QSPI0_REG(SPI_REG_IP)= %d\r\n",QSPI0_REG(SPI_REG_IP));
    if(QSPI0_REG(SPI_REG_IP)&0x01)
    {
        spi_transmit_receive(send_n);
        send_n++;
    }
//    printf("QSPI0_REG(SPI_REG_IP)= %d\r\n",QSPI0_REG(SPI_REG_IP));
    //
//    printf("QSPI_TXDATA(QSPI0)= %d\r\n",QSPI_TXDATA(QSPI0));
//    printf("QSPI_RXDATA(QSPI0)= %d\r\n",QSPI_RXDATA(QSPI0) & 0xff);
    printf("send_n= %d\r\n",send_n);

    if(send_n==10)
    {
        QSPI0_REG(SPI_REG_IE)&=~0x01;
    }
}



int main()
{
    printf("test start\r\n");
    __enable_irq();
	ECLIC_Register_IRQ(QSPI0_IRQn, ECLIC_NON_VECTOR_INTERRUPT,
                                    ECLIC_POSTIVE_EDGE_TRIGGER, 1, 1,
                                    QSPI0_handler);	


    qspi_sckmode_cfg(QSPI0,~(QSPI_SCKMODE_PHA|QSPI_SCKMODE_POL));

    qspi_fctrl_flashxip_disable(QSPI0);

    qspi_sckdiv_cfg(QSPI0,0x01);

    QSPI0_REG(SPI_REG_TXMARK) |=0x01;
//    QSPI0_REG(SPI_REG_TXMARK) |=0x03;
//    QSPI0_REG(SPI_REG_TXMARK) |=0x02;

//    QSPI0_REG(SPI_REG_RXMARK) |=0x01;

    QSPI0_REG(SPI_REG_IE)=0x01;

    while(send_n<10);
    #ifdef CFG_SIMULATION
        pass_fail_simulation(1);
        #endif 
    
    printf("test finish\r\n");
    while(1);

}